import { axios } from "@/tools/request"
import { path, wxAppid } from "@/config"

const userInfo = uni.getStorageSync("userInfo")
	? uni.getStorageSync("userInfo")
	: {
			id: "",
	  }

const state = {
	userInfo,
	token: uni.getStorageSync("token") || "",
}
const mutations = {
	setUserInfo(state, value) {
		const avatar = value.avatar
		if (avatar == "" || avatar == undefined || avatar == null) {
			value.avatar = ""
		} else {
			value.avatar = /^http/.test(avatar) ? avatar : path + avatar
		}

		state.userInfo = value
		uni.setStorageSync("userInfo", value)
		if (value.token) {
			state.token = value.token
			uni.setStorageSync("token", value.token)
			uni.setStorageSync("refresh_token", value.refreshToken)
		}
	},
	logout(state) {
		Object.keys(this.state).map(key => {
			this._mutations[key + "/logout"] && this.commit(key + "/logout")
		})
		state.userInfo = {}
		uni.removeStorageSync("userInfo")
		uni.removeStorageSync("token")
		uni.removeStorageSync("refresh_token")

		const page = getCurrentPages().pop()
		if (page?.route === "pages/login/index") {
			return
		}

		uni.reLaunch({
			url: "/pages/login/index",
		})
	},
	toggleVisible(state, visible = !state.visible) {
		state.visible = visible
	},
}
const actions = {
	async reloadUserInfo({ state, commit }) {
		if (!uni.getStorageSync("token")) {
			return Promise.reject("没有登录")
		}
		const memberInfo = await axios.get("/api/member/member/memebrInfo")
		commit("setUserInfo", memberInfo)
		return memberInfo
	},
}
const getters = {
	isLogin(state) {
		return !!state.userInfo.id && !!uni.getStorageSync("token")
	},
}
export default {
	state,
	mutations,
	actions,
	getters,
}
